package net

import (
	"fmt"
	"net"

	"github.com/oschwald/maxminddb-golang"
)

func NewIpMaxminddb(path string) *ipMaxminddb {
	db, err := maxminddb.Open(path)
	if err != nil {
		panic(err)
	}
	defer func(db *maxminddb.Reader) {
		err := db.Close()
		if err != nil {
			panic(err)
		}
	}(db)

	return &ipMaxminddb{
		path: path,

		db: db,
	}
}

type ipMaxminddb struct {
	path string

	db *maxminddb.Reader
}

func (r *ipMaxminddb) Lookup(ipString string) {
	ip := net.ParseIP(ipString)

	// var record any
	var record struct {
		Country struct {
			ISOCode string `maxminddb:"iso_code"`
		} `maxminddb:"country"`
	}

	err := r.db.Lookup(ip, &record)
	if err != nil {
		panic(err)
	}

	// record.Country.ISOCode
}
func (r *ipMaxminddb) Networks() {
	record := struct {
		Domain string `maxminddb:"connection_type"`
	}{}

	_, network, err := net.ParseCIDR("1.0.0.0/8")
	if err != nil {
		panic(err)
	}
	networks := r.db.NetworksWithin(network, maxminddb.SkipAliasedNetworks)
	// networks := r.db.Networks(maxminddb.SkipAliasedNetworks)
	for networks.Next() {
		subnet, err := networks.Network(&record)
		if err != nil {
			panic(err)
		}
		fmt.Println(subnet.String(), record.Domain)
	}
	if networks.Err() != nil {
		panic(networks.Err())
	}
}
